﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Mysoft.MyCM.Web.Controllers
{
	[AttributeUsage(AttributeTargets.All, AllowMultiple = true)]
	public class MAuthorizationFilterAttribute : AuthorizeAttribute, IAuthorizationFilter
	{
		/// <summary>
		/// Mysoft.Fix 身份验证过滤器
		/// </summary>
		/// <param name="requestType"></param>
		/// <param name="selectedCustomerValidation"></param>
		public MAuthorizationFilterAttribute(MRequestType requestType, MValidateType selectedCustomerValidation)
		{
			this.RequestType = requestType;
			this.SelectedCustomerValidation = selectedCustomerValidation;
		}

		public override void OnAuthorization(AuthorizationContext filterContext)
		{
			//base.OnAuthorization(filterContext);
			// 校验登录身份
			var param = MRequestParam.GetRequestParam(filterContext.Controller.ViewData);
			if (param.LogonUser == null)
			{
				switch (this.RequestType)
				{
					case MRequestType.Ajax:
						filterContext.Result = new JsonResult()
						{
							Data = new M.Web.AjaxHttpResult()
							{
								Result = false,
								UserData = "亲~没有登录是不能进行操作的"
							}
						};
						break;
					default:
						filterContext.HttpContext.Response.Redirect(string.Format("/User/Switch?returnUrl={0}", M.Web.Util.UrlEncode(param.CurrentWindowLocation)), true);
						break;
				}
			}
			// 设置用户信息
			filterContext.Controller.ViewBag.LogonUserDept = string.Format("{0}（{1}）", param.LogonUser.Name, param.LogonUser.Code);

			// 校验是否已选择客户
			if (string.IsNullOrEmpty(param.SelectedCustomerCode))
			{
				if (this.SelectedCustomerValidation == MValidateType.Validate)
				{
					// 仅需要在页面请求时处理
					filterContext.HttpContext.Response.Redirect("/Customer/Switch", true);
				}
			}
			// 设置客户选择信息
			filterContext.Controller.ViewBag.SelectedCustomerCode = param.SelectedCustomerCode;
		}

		/// <summary>
		/// 页面请求类型
		/// </summary>
		public MRequestType RequestType { get; private set; }
		/// <summary>
		/// 选择客户的验证类型
		/// </summary>
		public MValidateType SelectedCustomerValidation { get; private set; }
	}
}